<?php

namespace fastphp\util;

use fastphp\facade\Request;
use Firebase\JWT\ExpiredException;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtHandler
{
    //token秘钥
    protected string $key = 'vVR1LmHiQm1Dy94Vk';

    /**
     * 生成token
     * @param string $key 令牌
     * @param array $data 参数
     * @return string    token字符串
     */
    function encode(array $data = []): string
    {
        $payload = array(
            "iss" => "http://www.test.com", // 签发者
            "aud" => "http://www.test.com", // 接收方
            "iat" => time(), // 签发时间
            "nbf" => time(), // 生效时间
            "data" => $data,
            "exp" => time() + (60 * 60), // 过期时间 设置1小时
        );

        return JWT::encode($payload, $this->key, 'HS256');
    }

    public function decode($name = 'Auth')
    {
        $request = Request::getInstance();
        $token = $request::header($name);
        if (!$token) {
            return json_encode(['code' => 400, 'msg' => '认证失败，缺少token！']);
        }
        try {
            $decoded = JWT::decode($token, new Key($this->key, 'HS256'));
            // 将解码后的数据放入请求中，以便后续使用
            return (array)$decoded->data;
        } catch (ExpiredException $e) {
            return json_encode(['code' => 400, 'msg' => '认证过期，没有权限！']);
        } catch (\Exception $e) {
            return json_encode(['code' => 400, 'msg' => '认证无效，没有权限！']);
        }
    }
}